package com.hmdp.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<ShopType> queryTypeList() {
        List<String> shopTypeList = stringRedisTemplate.opsForList().range("cache:shop:list", 0, -1);
        if(CollUtil.isNotEmpty(shopTypeList)){
            return shopTypeList.stream().map(shopType -> {
                return JSONUtil.toBean(shopType, ShopType.class);
            }).collect(Collectors.toList());
        }
        List<ShopType> typeList =
                query().orderByAsc("sort").list();
        if (CollUtil.isEmpty(typeList)){
            throw new RuntimeException("没有查询到数据");
        }
        List<String> cacheShopType = typeList.stream().map(shopType -> {
            return JSONUtil.toJsonStr(shopType);
        }).collect(Collectors.toList());
        stringRedisTemplate.opsForList().leftPushAll("cache:shop:list", cacheShopType);

        return typeList;
    }
}
